﻿using Aker.DevTeam;
using Aker.Sistem;
using BI300SdkDllCS;
using DevExpress.XtraEditors;
using System;
using System.Collections.Generic;
using System.Text;

namespace Pidion
{
    public class Device
    {
        public Device()
        { }

        int Handle;
        BI300SdkDllCS.BtBarcode device = new BtBarcode();
        public delegate void BarcodeReadHandler(int Barcode);
        public event BarcodeReadHandler BarcodeRead;

        public string Connect(int PortNumber)
        {
            int errorCode = -1;
            int newHandle = 0;
            try
            {
                newHandle = device.Initialize(PortNumber, ref errorCode, onDisconnected, onBarcodeRead);
            }
            catch
            { }

            if (newHandle != 0)
                Handle = newHandle;

            return GetResultMessage(errorCode);
        }

        public string Disconnect()
        {
            //return "-";
            try
            {
                int result = device.Deinitialize(Handle, true);
                return GetResultMessage(result);
            }
            catch (Exception ex)
            {
                return ex.ToString();
            }
        }

        public string ClearAllData()
        {
            int result = device.ClearAllData(Handle);
            return GetResultMessage(result);
        }

        private int onBarcodeRead(int BtBarcodeHandle, byte[] OffsetNTime, string DecodeData, int nSize)
        {
            if (BarcodeRead != null)
            {
                string barcode = DecodeData.Trim();
                barcode = barcode.Substring(0, barcode.Length - 1);

                BarcodeRead(int.Parse(barcode));
            }


            return 0;
        }

        private int onDisconnected(int BtBarcodeHandle)
        {
            return 0;
        }



        public List<string> GetData()
        {
            List<string> items = new List<string>();

            int itemCount = 0;
            int symbolCode = 0;

            int result = device.PrepareCollecting(Handle, ref itemCount, onDataPrepared);
            if (result == 0)
            {
                byte[] Time = new byte[7];
                StringBuilder sb = new StringBuilder();
                int decodeSize = 0;

                for (int i = itemCount - 1; i > -1; i--)
                {
                    int itemResult = device.CollectingOnce(Handle, i, ref symbolCode, Time, sb, ref decodeSize);
                    if (itemResult == 0)
                    {
                        string strBarcode = sb.ToString().Substring(0, sb.Length - 1);
                        int barcode = int.Parse(strBarcode);
                        items.Add(barcode.ToString());
                    }
                    else
                    {
                        string itemError = GetResultMessage(itemResult);
                        items.Add(itemError);
                    }
                }
            }
            else
            {
                string error = GetResultMessage(result);
                items.Add(error);
            }

            return items;
        }

        public Dictionary<int, int> GetRafYerlesim()
        {
            Dictionary<int, int> result = new Dictionary<int, int>();
            List<string> items = GetData();

            int lastShelfId = 0;
            for (int i = 0; i < items.Count; i++)
            {
                try
                {

                    int barcode = int.Parse(items[i]);

                    if (barcode > 1000000 && barcode < 2000001)
                    {
                        lastShelfId = barcode;
                    }
                    else if (barcode > 2000000 && barcode < 3000001)
                    {
                        if (lastShelfId > 0)
                        {
                            if (result.ContainsKey(barcode))
                                result.Remove(barcode);

                            result.Add(barcode, lastShelfId);
                        }
                    }
                }
                catch (Exception ex)
                {
                    XtraMessageBox.Show("HATA: [" + items[i] + "] - " + ex.ToString());
                    throw ex;
                }
            }
            return result;
        }

        public Dictionary<int, int> GetIpYerlesim()
        {
            Dictionary<int, int> result = new Dictionary<int, int>();
            List<string> items = GetData();

            int lastShelfId = 0;
            for (int i = 0; i < items.Count; i++)
            {
                try
                {

                    int barcode = int.Parse(items[i]);

                    if (barcode > 1000000 && barcode < 2000001)
                    {
                        lastShelfId = barcode;
                    }
                    else if (barcode > 8000000 && barcode < 10000001)
                    {
                        if (lastShelfId > 0)
                        {
                            if (result.ContainsKey(barcode))
                                result.Remove(barcode);

                            result.Add(barcode, lastShelfId);
                        }
                    }
                }
                catch (Exception ex)
                {
                    XtraMessageBox.Show("HATA: [" + items[i] + "] - " + ex.ToString());
                    throw ex;
                }
            }
            return result;
        }




        private int onDataPrepared(int nTotalCollectSize, int nPresentCollectCnt)
        {
            return 0;
        }

        public string GetResultMessage(int val)
        {
            if (val == 0x00)
                return "SUCCESS";
            if (val == -0x01)
                return "FAIL";
            if (val == -0x02)
                return "PORT_PARAM_ERROR";
            if (val == -0x03)
                return "PORT_NOT_FOUND";
            if (val == -0x04)
                return "PORT_ACCESS_DENIED";
            if (val == -0x05)
                return "PORT_NOT_CLOSED";
            if (val == -0x06)
                return "NO_OPEN_PORT";
            if (val == -0x07)
                return "ALREADY_CONNECTED";
            if (val == -0x08)
                return "COMMUNICATION_PACKET_ERROR";
            if (val == -0x09)
                return "COMMUNICATION_TIMEOUT_ERROR";
            if (val == -0x0A)
                return "UNREGISTER_DEVICE_NOTIFY";
            if (val == -0x0C)
                return "USER_DISCONNECTED";
            if (val == -0x0D)
                return "NO_RUN_COLLECTING";
            if (val == -0x0E)
                return "NO_READ_DATA";
            if (val == -0x0F)
                return "OTHER_FUNC_RUN";
            if (val == -0x10)
                return "INVALID_BIHANDLE";
            if (val == -0x11)
                return "PORT_DISCONNECTED";
            if (val == -0x12)
                return "INVALID_ARGUMENT";
            if (val == -0x13)
                return "RECV_PACKET_ERROR";
            if (val == -0x14)
                return "INVALID_SYMBOL";
            if (val == -0x15)
                return "INVALID_SYMBOL_OPTION";
            if (val == -0x16)
                return "INVALID_SYMBOL_VALUE ";

            return val.ToString();
        }

        //public DateTime GetTime(byte[] bytes)
        //{
        //    int year = 0;
        //    int month = 0;
        //    int day = 0;
        //    int hour = 0;
        //    int min = 0;
        //    int sec = 0;
        //    int dayOfWeek = 0;
        //    int offset = 0;

        //    if (bytes.Length == 7)
        //    {
        //        year = bytes[0] + 1900;
        //        month = bytes[1] + 1;
        //        day = bytes[2];
        //        hour = bytes[3];
        //        min = bytes[4];
        //        sec = bytes[5];
        //        dayOfWeek = bytes[6];
        //    }
        //    else if (bytes.Length == 8)
        //    {
        //        offset = bytes[0];
        //        year = bytes[1] + 1900;
        //        month = bytes[2] + 1;
        //        day = bytes[3];
        //        hour = bytes[4];
        //        min = bytes[5];
        //        sec = bytes[6];
        //        dayOfWeek = bytes[7];
        //    }

        //    return new DateTime(year, month, day, hour, min, sec);
        //}

        public List<Barkod> GetHamVeri()
        {
            List<Barkod> items = new List<Barkod>();

            int itemCount = 0;
            int symbolCode = 0;

            int result = device.PrepareCollecting(Handle, ref itemCount, onDataPrepared);
            if (result == 0)
            {
                byte[] Time = new byte[7];
                StringBuilder sb = new StringBuilder();
                int decodeSize = 0;

                for (int i = itemCount - 1; i > -1; i--)
                {
                    int itemResult = device.CollectingOnce(Handle, i, ref symbolCode, Time, sb, ref decodeSize);
                    Barkod barkod = new Barkod();

                    if (itemResult == 0)
                    {
                        string strBarcode = sb.ToString().Substring(0, sb.Length - 1);
                        barkod.Kod = strBarcode.ToIntNN();
                        barkod.SembolKodu = symbolCode;
                        barkod.SetTarih(Time);

                        items.Add(barkod);
                    }
                    else
                    {
                        string error = GetResultMessage(itemResult);
                        //PidionBarkod pb = new PidionBarkod();
                        barkod.Hata = error;
                        items.Add(barkod);
                        //throw new ApplicationException(error);
                    }
                }
            }
            else
            {
                string error = GetResultMessage(result);
                Barkod barkod = new Barkod();
                barkod.Tarih = new DateTime(2000,1,1);
                barkod.Hata = error;
                items.Add(barkod);
                //throw new ApplicationException(error);
            }

            return items;
        }
    }
}
